<template>
	<div class="app-container editUser" v-loading="loading">
		<el-form ref="form" :model="form" :rules="rules" label-width="108px">
			<div class="authHeader">
				<h3 class="authTitle">用户基本信息</h3>
				<el-button v-if="isEdit" type="primary" icon="el-icon-edit" size="mini" @click="readonly = !readonly">{{ readonly ? '编辑基础信息' : '关闭信息编辑'}}</el-button>
			</div>
			<el-row>
				<el-col :span="6">
					<el-form-item label="用户名称" prop="userName">
						<el-input v-model="form.userName" placeholder="请输入用户名称" :disabled="form.userId > 0" />
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="真实姓名" prop="realname">
						<el-input v-model="form.realName" :disabled="readonly" placeholder="输入真实姓名" />
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="密码" prop="password">
						<el-input v-model="form.password" placeholder="请输入用户密码" type="password" :disabled="form.userId > 0" />
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="重复密码" prop="comfirmPassword">
						<el-input v-model="form.comfirmPassword" placeholder="请再次输入用户密码" type="password" :disabled="form.userId > 0" />
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="邮箱" prop="email">
						<el-input v-model="form.email" :disabled="readonly" placeholder="请输入邮箱" maxlength="50" />
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="联系电话" prop="phonenumber">
						<el-input v-model="form.phonenumber" :disabled="readonly" placeholder="请输入联系电话" maxlength="11" />
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="角色" prop="roleIds">
						<el-select v-model="form.roleIds" placeholder="请选择" style="width:100%;" :disabled="readonly">
							<el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.status == 1"></el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="分组" prop="groupIds">
						<el-select v-model="form.groupIds" @change="groupSelect" multiple filterable style="width:100%;" :disabled="readonly">
							<el-option v-for="item of groupList" :label="item.groupName" :value="item.groupId" :key="item.groupId"></el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="Token" prop="token">
						<el-input v-model="form.token" disabled></el-input>
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="创建时间/最后一次登录时间" prop="createTime">
						<el-input v-model="lastModifyTime" disabled></el-input>
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="状态" prop="status">
						<el-input v-model="form.status" disabled></el-input>
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="登录次数" prop="loginTimes">
						<el-input v-model="form.loginTimes" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-tabs v-model="activeName" @tab-click="handleClick">
				<el-tab-pane label="数据权限分配" name="1">
					<user-rules-data v-model="treeData" :is-edit="isEdit" @change="onChangeTreeData"></user-rules-data>
				</el-tab-pane>
				<el-tab-pane label="API服务权限分配" name="2">
					<user-rules-api ref="userRulesApi" v-model="apiRulesData" :user-id="userId"></user-rules-api>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		
		<div style="text-align:center;margin-top:36px;">
			<el-button type="primary" @click="submitForm">确 定</el-button>
			<el-button @click="cancel">取 消</el-button>
		</div>
		<auth-modal ref="authModal"></auth-modal>
	</div>
</template>

<script>
	import { getUser, addUser, updateUser } from "@/api/dataManagement/system/user";
	import { listGroup } from "@/api/dataManagement/system/group";
	import { groupTreeItem } from "@/api/dataManagement/system/dir";
	import authModal from './profile/authModal'
	import userRulesData from "@/views/dataManagement/system/user/components/UserRulesData"
	import UserRulesApi from "@/views/dataManagement/system/user/components/UserRulesApi"
	import { guid } from "@/utils/zkComm"

	export default {
		name: 'editUser',
		components: { authModal, userRulesData, UserRulesApi },
		data() {
			// 确认密码验证
			let validateComfirmPassword = (rule, value, callback) => {
				if (!this.form.password) {
					callback('请输入密码')
				} else if (!value) {
					callback('请再次输入密码')
				} else if (this.form.password != value) {
					callback('两次输入的密码不一致')
				} else {
					callback()
				}
			}
			return {
				loading: false,
				// 是否编辑状态
				isEdit: false,
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					userName: [
						{ required: true, message: "用户名称不能为空", trigger: "blur" }
					],
					nickName: [
						{ required: true, message: "用户昵称不能为空", trigger: "blur" }
					],
					password: [
						{ required: true, message: "用户密码不能为空", trigger: "blur" }
					],
					comfirmPassword: [{ required: true, validator: validateComfirmPassword, trigger: "blur" }],
					email: [
						{
							type: "email",
							message: "'请输入正确的邮箱地址",
							trigger: ["blur", "change"]
						}
					],
					phonenumber: [
						{
							pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
							message: "请输入正确的手机号码",
							trigger: "blur"
						}
					],
					roleIds: [
						{ required: true, message: "至少选择一个角色", trigger: "blur" }
					],
					groupIds: [
						{ required: false, message: "至少选择一个分组", trigger: "blur" }
					],
				},
				// 部门列表
				deptOptions: [],
				// 性别状态字典
				sexOptions: [],
				// 状态数据字典
				statusOptions: [],
				// 岗位选项
				postOptions: [],
				// 角色选项
				roleOptions: [],
				// 树结构
				treeData: [],
				treeLoading: false,
				// 分组列表
				groupList: [],
				// 根节点
				Fnode: {},
				activeName: '1',
				apiRulesData: [],
				readonly: false,
				userId: ''
			}
		},
		mounted() {
			this.edit()
			this.getDicts("sys_normal_disable").then(response => {
				this.statusOptions = response.data;
			});
			this.getDicts("sys_user_sex").then(response => {
				this.sexOptions = response.data;
			});

			// 获取分组列表
			this.getGroupList()
		},
		computed: {
			lastModifyTime() {
				return this.form.loginDate || this.form.createTime
			}
		},
		methods: {
			edit() {
				// console.log("用户Id",this.$route.query.id)
				// console.log("当前路由：",this.$route)
				this.userId = '';
				if (this.$route.name == "EditUser" && !this.$route.query.id) {
					this.$router.go(-1)
				} else if (this.$route.name == "EditUser" && this.$route.query.id) {
					this.userId = this.$route.query.id
					this.isEdit = true
				}

				this.readonly = this.isEdit

				this.loading = true
				getUser(this.userId).then(response => {
					this.roleOptions = response.roles;
					if (this.isEdit) {
						this.form = response.data;
						this.form.roleIds = response.roleIds[0];
						this.form.password = 123456
						this.form.comfirmPassword = 123456

						// 获取用户树节点
						let params = JSON.parse(JSON.stringify(response.data.tree.children))
						// this.treeData = this.traverseTree(params)
						this.treeData = this.formatTreeData(params)
						// this.groupSelect(response.data.groupIds)
						this.Fnode = response.data.tree
						delete this.Fnode.children
					}
					this.loading = false
				})
			},
			/** 提交按钮 */
			submitForm: function () {
				this.$refs["form"].validate(valid => {
					if (valid) {
						let params = { ...this.form }
						params.roleIds = [this.form.roleIds]
						let treeData = this.formatTreeDataBeforeSave(JSON.parse(JSON.stringify(this.treeData)))
						params.tree = { ...this.Fnode, children: treeData }
						params.comfirmPassword && delete params.comfirmPassword
						this.loading = true
						if (this.form.userId != undefined) {
							delete params.password
							updateUser(params).then(response => {
								this.msgSuccess("修改成功");
								this.deleteTagsView()
								this.$router.push({ path: '/manager/user/list' })
								this.loading = false
							}).catch(() => {
								this.loading = false
							});
						} else {
							addUser(params).then(response => {
								this.msgSuccess("新增成功");
								this.deleteTagsView()
								this.$router.push({ path: '/manager/user/list' })
								this.loading = false
							}).catch(() => {
								this.loading = false
							});
						}
					}
				});
			},
			// 取消按钮
			cancel() {
				this.deleteTagsView()
				this.$router.push({ path: '/manager/user/list' })
			},
			deleteTagsView() {
				let view = { ...this.$route }
				this.$store.dispatch('tagsView/delView', view).then(() => { })
			},
			getGroupList() {
				listGroup({ pageSize: 65535 }).then(res => {
					this.groupList = res.rows
				})
			},
			// 选择分组获取相关权限
			groupSelect(value) {
				if (value.length == 0) {
					this.treeData = []
					return false
				}

				let ids = ''
				value.forEach((item, index) => {
					if (index != 0) {
						ids += ','
					}
					ids += item
				})
				this.treeLoading = true
				groupTreeItem({ groupIds: ids }).then(res => {
					// console.log("res:",res)
					// this.treeData = this.traverseTree(res.data.children)
					this.treeData = res.data.children
					this.Fnode = res.data
					delete this.Fnode.children
					this.treeLoading = false
				}).catch(err => {
					this.treeLoading = false
				})
			},
			// 递归树状结构
			// traverseTree(data) {
			// 	if (!data) { return; }
			// 	for (let i = 0; i < data.length; i++) {
			// 		if (!data[i].isTable && data[i].children && data[i].children.length > 0) {
			// 			data[i].selectAll = ''
			// 		}
			// 		if (data[i].children && data[i].children.length > 0) {
			// 			this.traverseTree(data[i].children);
			// 		}
			// 	}
			// 	return data
			// },
			handleClick(value) {
				if (value.name == 2) this.$refs.userRulesApi.fetchData()
			},
			onChangeTreeData(value) {
				console.log("onChangeTreeData", value)
			},
			formatTreeData(treeData) {
				treeData.forEach((item, i) => {
					item.accessType = !item.accessType ? '000' : item.accessType
					item.uniqueid = guid()
					item = Object.assign({}, {}, item)
					treeData[i] = item
					if (item.children.length > 0) {
						return this.formatTreeData(item.children)
					}
				});
				return treeData;
			},
			formatTreeDataBeforeSave(treeData) {
				treeData.forEach((item, i) => {
					item.accessType = item.accessType == '000' ? null : item.accessType
					treeData[i] = item
					if (item.children.length > 0) {
						return this.formatTreeDataBeforeSave(item.children)
					}
				});
				return treeData;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.editUser {
		background: #ffffff;
		margin: 0 20px;
		padding: 16px;
	}
	.authHeader {
		display: flex;
		align-items: center;
		margin-bottom: 26px;
	}
	.authTitle {
		font-size: 16px;
		font-weight: 400;
		color: #5a5a5a;
		line-height: 20px;
		padding: 0 6px;
		border-left: 2px solid #1183f8;
	}
	::v-deep.el-form-item {
		padding-right: 10px;
	}
</style>